﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DetetiveKGB.Models;
using System.IO;
using System.Configuration;

namespace DetetiveKGB.Controllers
{
    public class ActorsController : Controller
    {
        public ActionResult Index()
        {
            List<ActorsModel> actorsModel = ActorsModel.ListAll();
            var res = actorsModel;
            return View(res);
        }

        //
        // GET: /Actor/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Actor/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Actor/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Actor/Edit/5
 
        public ActionResult Edit(int id)
        {
            if (id > 0)
            {
                var res = ActorsModel.Get(id);
                return View(res);
            }
            else
                return View();
        }

        //
        // POST: /Actor/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                string path         = string.Empty;
                string imgMessage   = string.Empty;
                int maxWidth        = Convert.ToInt32(ConfigurationManager.AppSettings["maxWidth"]);
                int maxHeight       = Convert.ToInt32(ConfigurationManager.AppSettings["maxHeight"]);
                
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase postedFile = Request.Files[fileName];
                    if (!string.IsNullOrEmpty(postedFile.FileName))
                    {
                        System.Drawing.Image img = System.Drawing.Image.FromStream(postedFile.InputStream, true, true);
                        if (img.Width > maxWidth || img.Height > maxHeight)
                            imgMessage = string.Format("A imagem deve ter tamanho máximo de {0}px por {1}px.", maxWidth, maxHeight);
                        postedFile.SaveAs(Server.MapPath("~/Content/images/Actors/") + Path.GetFileName(postedFile.FileName));
                        path = Path.GetFileName(postedFile.FileName);
                    }
                }

                ActorsModel result = null;
                if (id == 0)
                    result = new ActorsModel();
                else
                    result = ActorsModel.Get(id);
                if (string.IsNullOrEmpty(collection.Get("Name").Trim()))
                    ModelState.AddModelError("Name", "O nome do personagem é obrigatório.");
                if (ActorsModel.Exists(id, collection.Get("Name").Trim()))
                    ModelState.AddModelError("Name", "Já existe personagem cadastrado com esse nome.");
                if (!string.IsNullOrEmpty(imgMessage))
                    ModelState.AddModelError("Image", imgMessage);

                if (!ModelState.IsValid)
                    return View(result);
                
                result.Name         = collection.Get("Name").Trim();
                result.Description  = collection.Get("Description");
                string image        = !string.IsNullOrEmpty(result.Image) && !result.Image.Contains("not_found") ? result.Image.Replace("../../Content/images/Actors/", string.Empty) : null;
                result.Image        = !string.IsNullOrEmpty(path) ? path : image;
                result.Enabled      = collection.Get("Enabled").Contains("true");
                
                if (id == 0)
                    result.Add();
                else
                    result.Update();

                return RedirectToAction("Index");
            }
            catch
            {
                return View("Edit");
            }
        }

        //
        // GET: /Actor/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Actor/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
